import * as AgentApi from '@/api/call/agent'
import { usePhoneStore } from '@/store/modules/phone'
import { formatDate } from '@/utils/formatTime'
/**
 * 卡尔无线话机盒子sdk
 * 1. 使用ws连接到本地
 * 2. 使用指令交互，完成时间同步，呼叫，来电和去电接听
 */

export function useBoxPhone() {
  let WS = null

  const SESSION = null

  const useStore = usePhoneStore()

  // 会话状态
  const SESSION_STATUS = {
    RINGING: 'ringing',
    PROGRESS: 'progress',
    ACCEPTED: 'accepted',
    REJECT: 'reject',
    CANCEL: 'cancel',
    FAILED: 'failed',
    ENDED: 'ended',
    MISSED: 'missed'
  }
  const TYPE_IN = 'incoming'
  const TYPE_OUT = 'outgoing'
  const TYPE = {
    incoming: 'incoming',
    outgoing: 'outgoing'
  }

  // 话机连接成功回调
  // 连接成功后，需要配置：1.获取icid、2.获取index 3.设置话单上传路径
  const onWSConnected = () => {
    if (WS) {
      ElMessage.success('无线话机模式已激活')
      WS.send('{"cmd":"getIccid"}')
      WS.send('{"cmd":"getSimIndex"}')
      const recordData = {
        cmd: 'setCallrecord',
        pid: 'petepower',
        userWid: '123',
        // recordFileUrl: 'http://admin.datacreationall.com/call/callbackV3/onRecordUpdate'
        recordFileUrl: 'https://scrm-admin.jzsaas.com/admin-api/call/notify/boxUpload',
        callrecordUrl: 'https://scrm-admin.jzsaas.com/admin-api/call/notify/4'
      }
      WS.send(JSON.stringify(recordData))
    }
  }

  const setIccid = (number) => {
    //
  }

  let session = null

  const onConnecting = async (data) => {
    console.info('onConnecting ---- ', data)
    if (data.success) {
      // 发起日志
      await AgentApi.mapCallId({
        reqNo: data.callid,
        callId: data.callId
      })
      // 创建 session
      session = {
        type: TYPE_OUT, // 类型： incoming , outgoing
        callee: data.number || '', // 被叫
        reqNo: data.callid || '', // 请求id
        status: SESSION_STATUS.RINGING, // 状态
        time: 0 // 通话时长
      }

      useStore.setSession(session)
    } else {
      ElMessage.error(data.message)
    }
  }

  const onCalling = (data) => {
    console.info('on onCalling ----- ', data)
  }

  const onAccepted = (data) => {
    session = useStore.getSession
    session.status = SESSION_STATUS.ACCEPTED
    useStore.setSession(session)
    console.info('on onAccepted ----- ', data)
  }
  const onEnded = (data) => {
    session = useStore.getSession
    session.status = SESSION_STATUS.ENDED
    useStore.setSession(session)
    console.info('on onEnded ----- ', data)
  }

  const onRecord = (data) => {
    console.info('on onRecord ----- ', data)
  }

  const setSimIndex = (data) => {
    console.info('on setSimIndex ----- ', data)
  }

  const onEndChgSim = (data) => {
    console.info('on onEndChgSim ----- ', data)
  }

  const connectWebsocket = () => {
    WS = new WebSocket(`ws://127.0.0.1:8800`)
    WS.onmessage = function (e) {
      // console.info('onMessage ---- ', e)

      const { data } = e
      const msg = JSON.parse(data)
      const { cmd } = msg

      switch (cmd) {
        case 'USB':
          if (msg.connected == true) {
            onWSConnected()
          } else {
            useStore.clearAll()
            alert('连接失败，检查话机指示灯以及电脑是否已登录PhoneService')
          }
          break
        case 'getIccid':
          setIccid(msg.number)
          break
        // 拨号成功同步返回
        case 'ATD':
          onConnecting(msg)
          break
        // 话机去电
        case 'CORG':
          onCalling(msg)
          break
        // 话机来电
        case 'CALLING':
          onRinging(msg)
          break
        // 话机来电或去电接通
        case 'CBEGIN':
          onAccepted(msg)
          break

        // 话机挂机返回
        case 'CEND':
          onEnded(msg)
          break

        // 生成录音
        case 'stoprecord':
          onRecord(msg)
          break

        case 'getSimIndex':
          setSimIndex(msg)
          break

        case 'endChgSim':
          onEndChgSim(msg)
          break
      }
    }

    WS.onopen = function () {
      console.info('on Connect ws: >>> ws is open ')
      WS.send('{"cmd":"LINK"}')
      const time = formatDate(new Date(), 'YYYYMMDDHHmmss')
      WS.send('{"cmd":"time","time": "' + time + '"}')
    }

    WS.onclose = function () {
      useStore.clearAll()
      console.info('on Connect ws: >>> ws is close ')
      // onLeave();
      ElMessage.error('无线话机盒子连接失败')
    }
    WS.onerror = function (e) {
      useStore.clearAll()
      console.error('ws error: >>', e)
    }
  }

  const answer = () => {
    WS && WS.send('{"cmd":"ATA"}')
  }

  const hangup = () => {
    WS && WS.send('{"cmd":"ATH"}')
  }

  const call = async (params) => {
    // 先去请求call接口
    const data = await AgentApi.simpleCall(params)
    localStorage.setItem('CALL_TASK_REQ_NO', data.reqNo)
    const callPost = {
      cmd: 'ATD',
      number: params.callee,
      callid: data.reqNo
    }
    if (!WS) {
      connectWebsocket()
      ElMessage.warning('话机丢失连接，正在重新建立连接...')
    } else {
      WS.send(JSON.stringify(callPost))
    }
    useStore.setAgentStatus('login')
  }

  const reg = async () => {
    connectWebsocket()
  }

  return {
    reg,
    call,
    hangup
  }
}
